<?php

namespace app\admin\controller\course;

use app\admin\model\course\Order;
use app\admin\model\course\OrderGoods;
use app\common\controller\Backend;
use app\common\model\User;
use fast\Form;
use think\Db;

/**
 * 签到管理
 *
 * @icon fa fa-circle-o
 */
class OrderSign extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\course\OrderSign
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\course\OrderSign();
        $adminStatusList = $this->model->getAdminStatusList();
        $statusList = $this->model->getStatusList();
        $this->view->assign("statusList", $adminStatusList);
        $this->assignconfig("statusList", $statusList);


        $schoolModel = new \app\admin\model\user\School();
        $schoolGroup = $schoolModel->getAllSchool();
        $this->assignconfig("schoolGroup",$schoolGroup);

        $order_id = $this->request->param('order_id');

        $this->assignconfig('order_id', $order_id);
        $this->view->assign('order_id', $order_id);
    }

    /**
     * 手动录单
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);



        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        $orderModel = new \app\admin\model\course\Order();
        $orderGoodsModel = new OrderGoods();

        Db::startTrans();
        try {
            $condition = [
                "order_goods.id" => $params['order_goods_id'],
            ];
            $orderGoods = $orderGoodsModel->getTimeTable($condition,$params['day'],false);
            if($params['status'] == $this->model::STATUS_ACTIVITY){
                if($params['class_hour'] <= 0){
                    $this->error("活动签到请填写消耗课时");
                }
                $orderGoods['class_hour'] = $params['class_hour'];
            }
            //检测今天有没有签到
            switch ($params['status']){
                case $this->model::STATUS_SIGN:
                case $this->model::STATUS_ADMIN_SIGN:
                case $this->model::STATUS_ACTIVITY:
                    $sign_data[] = $this->model->sign($orderGoods,$params['day'],$params['status'],$params['leave_content'],true,true);
                    if(count($sign_data) <= 0){
                        exception("请选择学员进行签到");
                    }

                    $this->model->insertAll($sign_data);

                    //检测下订单是否完成
                    $order = new Order();
                    foreach ($sign_data as $key => $value){
                        $order->checkOrderSuccessStatus($value['order_id']);
                    }
                    break;
                case $this->model::STATUS_LEAVE:
                    $this->model->sign($orderGoods,$params['day'],$params['status'],$params['leave_content']);
            }

            Db::commit();
        }catch (\Exception $exception){
            Db::rollback();
            $this->error($exception->getMessage());
        }


        $this->success();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();


            $list = $this->model
                ->with(['course','student','order_goods','teacher','buketeacher'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);

            foreach ($list as $row) {

                $row->getRelation('course')->visible(['name']);
                $row->getRelation('student')->visible(['name']);
                $row->getRelation('order_goods')->visible(['time_name','school_name']);
                $row->getRelation('teacher')->visible(['nickname']);
                $row->getRelation('buketeacher')->visible(['nickname']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

}
